#include "core_plugin.h"

static struct core_plugin *core_plugin_t = NULL;

void * read_stdio() 
{
	int pos;
	char c = 0;
	char msg[256];

	core_plugin_t->is_running = 1;

	while ( core_plugin_t->is_running ) {

		pos = 0;
		printf (": ");
		do {
			c = getchar(); /*getchar is blocking, TODO: make sure that */ 
			msg[pos] = c;	/* this thread will be killed*/
			pos++;
		} while ( c != '\n' );

		msg[ pos ] = '\0';

		if ( !strncmp( msg, "/quit", 5 ) ) 
			core_plugin_t->is_running = 0;
		
		if ( !strncmp( msg, "/", 1 ) ) {
			core_plugin_t->notify_plugin_control( msg );
			continue;
		}
		else 
			core_plugin_t->plugin->send_message( msg );
	}

	pthread_exit( NULL );
}

static void handle_msg( char *msg ) 
{
	char *part;
	char reply[100] = "PONG :";

	printf("Core plugin received: %s\n", msg );
	
	if ( !strncmp( msg, "PING", 4 ) ) {
		
		printf("PING received \n");
  	part = strtok ( msg,":" );
		part = strtok (NULL, ":");
		strcat( reply, part );
		core_plugin_t->plugin->send_message( msg );
	}
}

struct core_plugin * new_core_plugin()
{
	int res;

	core_plugin_t = (struct core_plugin*) malloc( sizeof( struct core_plugin ) );
	if ( core_plugin_t == NULL ) {
		fprintf( stderr, "Core plugin allocation failed, out of memory. \n" );		
		return NULL;
	}

	core_plugin_t->plugin = (struct plugin*) malloc( sizeof( struct plugin ) );
	if ( core_plugin_t->plugin == NULL ) {
		fprintf( stderr, "Core plugin->plugin allocation failed, out of memory. \n" );		
		return NULL;
	}

	core_plugin_t->plugin->id = "core_plugin";
	core_plugin_t->plugin->handle_msg = handle_msg;

	if ( ( res = pthread_create( &core_plugin_t->thread, NULL, read_stdio, NULL) ) ) {
		fprintf(stderr, "Core thread creation failed: %d\n", res);
		return NULL;
	}

	core_plugin_t->plugin->implementer = (void*)core_plugin_t;
	core_plugin_t->free = delete_core_plugin;

	return core_plugin_t;
}

void delete_core_plugin() 
{
	if ( core_plugin_t != NULL ) {
		if ( core_plugin_t->plugin != NULL )
			free( core_plugin_t->plugin );
		free( core_plugin_t );
	}
}

void stop_thread() 
{
	core_plugin_t->is_running = 0;
}
